package com.cgt.xiaotao.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgt.common.utils.BeanUtils;
import com.cgt.common.utils.UserContext;
import com.cgt.xiaotao.user.domain.dto.UserAddressDTO;
import com.cgt.xiaotao.user.domain.po.UserAddress;
import com.cgt.xiaotao.user.mapper.UserAddressMapper;
import com.cgt.xiaotao.user.service.IUserAddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {

    // 添加用户地址
    @Override
    public void saveAddress(UserAddressDTO dto) {
        Long userId = UserContext.getUser();
        UserAddress userAddress = BeanUtils.copyBean(dto, UserAddress.class);
        userAddress.setUserId(userId);
        this.save(userAddress);
    }

    @Override
    public void updateAddress(UserAddressDTO dto) {
        Long userId = UserContext.getUser();
        UserAddress userAddress = BeanUtils.copyBean(dto, UserAddress.class);
        userAddress.setUserId(userId);
        // 打印 userAddress 对象，检查 id 是否正确
        System.out.println("Updating user address: " + userAddress);
        this.updateById(userAddress);
    }

    @Override
    public List<UserAddressDTO> getList() {
        Long userId = UserContext.getUser();
        List<UserAddressDTO> list = this.lambdaQuery()
                .eq(UserAddress::getUserId, userId)
                .list()
                .stream()
                .map(item -> {
                    UserAddressDTO dto = new UserAddressDTO();
                    BeanUtils.copyProperties(item, dto);
                    return dto;
                }).collect(Collectors.toList());
        return list;
    }

    @Override
    public void deleteAddress(Long id) {
        Long userId = UserContext.getUser();
        this.remove(new LambdaQueryWrapper<UserAddress>()
                .eq(UserAddress::getId, id)
                .eq(UserAddress::getUserId, userId));
    }
}
